﻿using ComponentFactory.Krypton.Navigator;
using ComponentFactory.Krypton.Toolkit;
using ComponentFactory.Krypton.Ribbon;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Teigha.DatabaseServices;
using SRB.Tg.Cad_Bll;
using System.IO;
using SRB.Tg.Common;
using SRB.Tg.Operate;
using SRB.Tg.Model;
using SRB.Tg.DrawingStandard;

namespace SRB.Tg.Cad
{
    public partial class MainForms : KryptonForm
    {
        public TeighaBase CAD = null;
        private int _heightUpDown;
        private int _widthLeftRight;
        private int _widthLeftRight0;
        private BackgroundWorker bworker = new BackgroundWorker();
        TeighaBase basef=null;
        public MainForms()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            
            bindblendent();
            QatUndo.Click += QatUndo_Click;
            QatDoit.Click += QatDoit_Click;

            kryptonContextMenuItem10.Click += KryptonContextMenuItem10_Click;
            kryptonContextMenuItem11.Click += KryptonContextMenuItem11_Click;
            kryptonContextMenuItem12.Click += KryptonContextMenuItem12_Click;

            kryptonHeaderGroup3.ButtonSpecs[0].Click += new EventHandler(OnUpDown);
            kryptonHeaderGroup1.ButtonSpecs[0].Click += new EventHandler(OnLeftRight);

            //Load_the_dwgordxf(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"Template\test.dwg", false);
            //CheckIsExistTgBase();
            gjInfo.ButtonSpecs[0].Click += new EventHandler(GJInfo_OnLeftRight);
            //执行具体的方法
            bworker.DoWork += Bworker_DoWork;
            this.kryptonRibbon.SelectedTab=srbRib;
            //InitPileCapTree();
            InitSubstructureInfo();
        }

        private void Bworker_DoWork(object sender, DoWorkEventArgs e)
        {
            //GJInfo_OnLeftRight(null, null);
            //GJInfo_OnLeftRight(null, null);
            //CheckIsExistTgBase();
        }

        private void MainForms_Load(object sender, EventArgs e)
        {
            IniOper.getInstance().LoadConifg();
            Extensions.curFont = IniOper.getInstance().CurFont;
            Extensions.Font = IniOper.getInstance().Font;
            Extensions.FontWidth = double.Parse(IniOper.getInstance().FontWidth);
            Extensions.curMapSheet = IniOper.getInstance().CurMapSheet;
            Extensions.bottomHeight = double.Parse(IniOper.getInstance().BottomHeight);
            Extensions.topHeight = double.Parse(IniOper.getInstance().TopHeight);
            Extensions.leftWidth = double.Parse(IniOper.getInstance().LeftWidth);
            Extensions.rightWidth = double.Parse(IniOper.getInstance().RightWidth);
            Extensions.scaleList = IniOper.getInstance().ScaleList;
            Extensions.modelunit = IniOper.getInstance().ModelUnit;
            Extensions.layoutunit = IniOper.getInstance().LayoutUnit;
            InitDwgTemp();
            InitSaveDwgTemp();
            CheckIsExistTgBase();

            InitConfig.InitStandardConfig();

            CAD.Refresh();
            //GJInfo_OnLeftRight(null, null);
           
            //InitPileTree();
       
            InfoContainer.Update();
            //开始异步执行
            bworker.RunWorkerAsync();
            bworker.RunWorkerCompleted += Bworker_RunWorkerCompleted;
        }

        private void Bworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            GJInfo_OnLeftRight(null, null);
            GJInfo_OnLeftRight(null, null);
        }

        #region 初始化模板,以及保存临时模板
        public void InitDwgTemp()
        {
            string dic = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Temp\\";
            if (!Directory.Exists(dic))
            {
                Directory.CreateDirectory(dic);
            }
            else
            {
                Directory.Delete(dic, true);
                Directory.CreateDirectory(dic);
            }
        }

        public void InitSaveDwgTemp()
        {
            string dic = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "DrawingsList\\";
            if (!Directory.Exists(dic))
            {
                Directory.CreateDirectory(dic);
            }
            else
            {
                Directory.Delete(dic,true);
                Directory.CreateDirectory(dic);
            }
        }
        #endregion

        #region 撤销事件
        private void QatDoit_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD.Invoker.RedoStack();
            }
        }

        private void QatUndo_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD.Invoker.UndoStack();
            }
        } 
        #endregion

        #region 控件事件
        //打开
        private void kryGroupButopenfile_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == openFileDialog.ShowDialog(this))
            {
                //Load_the_dwgordxf(openFileDialog.FileName, false);
                loadDwgFiles(openFileDialog.FileName);
                GlobleFunc.tempDwgPath = openFileDialog.FileName;
            }
        }


        private void MainForms_FormClosed(object sender, FormClosedEventArgs e)
        {
            KryptonPageCollection krylist = kryNavigators.Pages;
            foreach (KryptonPage item in krylist)
            {
                TeighaBase basef = SelectDataGridView(item);
                if (basef != null)
                {
                    basef.Invoker.Dispose();
                    if (basef.graphics != null)
                        basef.graphics.Dispose();
                    if (basef.helperDevice != null)
                        basef.helperDevice.Dispose();
                    if (basef.database != null)
                        basef.database.Dispose();
                }
                
            }
            try
            {
                if (PublicClass.ServiceD != null)
                    PublicClass.ServiceD.Dispose();
            }
            catch { }
        }



        private void kryGroupButCreateDWG_Click(object sender, EventArgs e)
        {
            OpenDxfOrDwg();
        }

        public void OpenDxfOrDwg()
        {
            string tempFile = System.IO.Path.GetTempFileName();
            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Template\\dwgModel.dwg";
            FileInfo info = new FileInfo(path);
            info.CopyTo(tempFile, true);
            GlobleFunc.tempDwgPath = tempFile;
            Load_the_dwgordxf(tempFile, false);
            for (int i = kryNavigators.Pages.Count - 1; i >= 0; i--)
            {
                if (tempFile.Contains(kryNavigators.Pages[i].Name + ".tmp") || tempFile.Contains(kryNavigators.Pages[i].Name + ".dwg"))
                {
                    continue;
                }
                else
                {
                    kryNavigators.Pages.Remove(kryNavigators.Pages[i]);
                }
            }

            //目标删除指定元素name

            kryNavigators.Refresh();
        }
        public void loadDwgFiles(string tempFile)
        {
            //OpenDxfOrDwg();
            Load_the_dwgordxf(tempFile, false);

            for (int i = kryNavigators.Pages.Count - 1; i >= 0; i--)
            {
                if (tempFile.Contains(kryNavigators.Pages[i].Name + ".tmp") || tempFile.Contains(kryNavigators.Pages[i].Name + ".dwg"))
                {
                    continue;
                }
                else
                {
                    kryNavigators.Pages.Remove(kryNavigators.Pages[i]);
                }
            }

            kryNavigators.Refresh();
        }
        private void kryGroupButFontSet_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD = TeighaBase.getInstance(this);
                CAD.Parent = this;
                //CAD =new  TeighaBase();
                Fontstyles font = new Fontstyles(ref CAD);
                font.Show(this);
            }
        }

        private void kryRibself_adaption_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD.zoom_extents_handler();
            }
        }

        private void kryNavigators_SelectedPageChanged(object sender, EventArgs e)
        {
            basef = SelectDataGridView(kryNavigators.SelectedPage);
            GlobleFunc.lastDwgPath = GlobleFunc.tempDwgPath;
            if (basef != null)
            {
                //basef.Send_Change_Layout += Basef_Send_Change_Layout1;
                basef.Send_D_Complete += Basef_Send_D_Complete;
                basef.Send_Insert_UC += Basef_Send_Insert_UC;
                kryRibself_adaption.Enabled = true;
                kryAmplificationbtn.Enabled = true;
                kryShrinkbtn.Enabled = true;
                krypGroupButRoll.Enabled = true;
                kryGyroscopebtn.Enabled = true;

                kryptonRibbonGroupButton1.Enabled = true;
                kryGroupButFontSet.Enabled = true;

                kryShowLayers.Enabled = true;
                krypGroupCloseSelect.Enabled = true;
                kryGroupButCloseOther.Enabled = true;
                kryGroupButOpenAll.Enabled = true;

                CAD = basef;
                GlobleFunc.tempDwgPath = basef.DwgPath;
                HostApplicationServices.WorkingDatabase = basef.database;
                CAD.basepanel.Focus();
            }
            else
            {
                kryRibself_adaption.Enabled = false;
                kryAmplificationbtn.Enabled = false;
                kryShrinkbtn.Enabled = false;
                krypGroupButRoll.Enabled = false;
                kryGyroscopebtn.Enabled = false;

                kryptonRibbonGroupButton1.Enabled = false;
                kryGroupButFontSet.Enabled = false;

                kryShowLayers.Enabled = false;
                krypGroupCloseSelect.Enabled = false;
                kryGroupButCloseOther.Enabled = false;
                kryGroupButOpenAll.Enabled = false;

            }
        }

        private void Basef_Send_Insert_UC()
        {
            this.kryRibButEllipse.Checked = false;
            this.kryRibGButArc.Checked = false;
            this.kryRibGButHu.Checked = false;
            this.kryRibGButLine.Checked = false;
            this.kryRibGButMtext.Checked = false;
            this.kryRibGButPen.Checked = false;
            this.kryRibGButPoint.Checked = false;
            this.kryRibGButPoliy.Checked = false;
            this.kryRibGButText.Checked = false;
        }

        private void Basef_Send_D_Complete(bool isCheck)
        {
            this.kryptonRibbonDragBtn.Checked = isCheck;
        }

        private void Basef_Send_Change_Layout1(string dwgPath)
        {
            try
            {

                string tempFile = System.IO.Path.GetTempFileName();
                string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Template\\dwgModel.dwg";
                FileInfo info = new FileInfo(path);
                info.CopyTo(tempFile, true);
                //GlobleFunc.tempDwgPath = tempFile;
                loadDwgFiles(tempFile);
                System.Threading.Thread.Sleep(1000);
                loadDwgFiles(dwgPath);

                //string filename = new FileInfo(dwgPath).Name;
                //bool isLoad = false;
                //foreach(var page in kryNavigators.Pages)
                //{
                //    if(filename==page.Name+".tmp"|| filename == page.Name + ".dwg")
                //    {
                //        isLoad = true;
                //        break;
                //    }
                //}
                //if (!isLoad)
                //{
                //    Load_the_dwgordxf(dwgPath, false);

                //    //KryptonPageCollection krylist = kryNavigators.Pages;
                //    //KryptonPage page = krylist[0];
                //    //foreach (var item in krylist)
                //    //{
                //    //    if (GlobleFunc.lastDwgPath.Contains(item.Name))
                //    //    {
                //    //        page = item;
                //    //        break;
                //    //    }
                //    //}

                //    //page.Select();
                //    //page.ButtonSpecs[0].PerformClick();
                //    //page.Refresh();
                //    for (int i = kryNavigators.Pages.Count - 1; i >= 0; i--)
                //    {
                //        if (dwgPath.Contains(kryNavigators.Pages[i].Name + ".tmp") || dwgPath.Contains(kryNavigators.Pages[i].Name + ".dwg"))
                //        {
                //            continue;
                //        }
                //        else
                //        {
                //            kryNavigators.Pages.Remove(kryNavigators.Pages[i]);
                //        }
                //    }
                //    kryNavigators.Refresh();
                //}
            }
            catch (Exception ex)
            { }

        }

        async Task PutTaskDelay()
        {
            await Task.Delay(100);
            //Send_Change_Layout(path);
        }

        private void kryAmplificationbtn_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD.Set_zoom(3);
            }
        }

        private void kryShrinkbtn_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                double nums = (double)1 / (double)3;
                CAD.Set_zoom(nums);
            }
        }

        private void kryShowLayers_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                ManageLayer Manlay = new ManageLayer(ref CAD);
                Manlay.Show(this);
            }
        }

        private void krypGroupCloseSelect_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD.LayerHidePitchOn();
            }
        }

        private void kryGroupButCloseOther_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD.LayerHideExceptPitchOn();
            }
        }

        private void kryGroupButOpenAll_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                CAD.LayerShowAll();
            }
        }
        #endregion

        #region 自定义方法
        bool isLock = false;
        /// <summary>
        /// 加载dwg
        /// </summary>
        /// <param name="Path"></param>
        public void Load_the_dwgordxf(string Path, bool Tag)
        {
            if (!isLock)
            {
                isLock = true;              
                KryptonPage page = new KryptonPage();
                page.Name = System.IO.Path.GetFileNameWithoutExtension(Path);
                page.Text = System.IO.Path.GetFileNameWithoutExtension(Path);
                page.TextTitle = System.IO.Path.GetFileNameWithoutExtension(Path);
                page.ToolTipBody = Path;
                page.ToolTipTitle = Path;

                ButtonSpecAny bsa = new ButtonSpecAny();
                bsa.Tag = page;
                bsa.Type = PaletteButtonSpecStyle.Close;

                bsa.Click += new EventHandler(OnClosePage);
                page.ButtonSpecs.Add(bsa);

             
                page.ClearFlags(KryptonPageFlags.DockingAllowAutoHidden | KryptonPageFlags.DockingAllowDocked);

                //SingleCAD Speed = new SingleCAD(this);
                SingleCAD Speed = SingleCAD.getInstance(this);

                Speed.TopLevel = false;
                Speed.Parent = this;
                Speed.Tag = Tag;
                Speed.Dock = DockStyle.Fill;
                Speed.LoadPage(Path);
                Speed.FormBorderStyle = FormBorderStyle.None;
                //string name = "[" + System.IO.Path.GetFileNameWithoutExtension(Path) + "]";
                page.Controls.Add(Speed);
                Speed.Show();
                //for (int i = kryNavigators.Pages.Count - 1; i >= 0; i--)
                //{
                //    if (tempFile.Contains(kryNavigators.Pages[i].Name + ".tmp") || tempFile.Contains(kryNavigators.Pages[i].Name + ".dwg"))
                //    {
                //        continue;
                //    }
                //    else
                //    {
                //        kryNavigators.Pages.Remove(kryNavigators.Pages[i]);
                //    }
                //}
                //kryNavigators.Pages.Clear();
                kryNavigators.Refresh();
                kryNavigators.Invalidate();
              
                kryNavigators.Pages.Add(page);
                kryNavigators.SelectedPage = page;
                page.Select();

                page.Refresh();
                if (CAD != null)
                {
                    CAD.zoom_extents_handler();
                    InitConfig.InitStandardConfig();
                }
                kryNavigators.Refresh();

                isLock = false;
            }
        }

        /// <summary>
        /// 关闭page页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClosePage(object sender, EventArgs e)
        {
            KryptonPageCollection krylist = kryNavigators.Pages;
            if (krylist.Count > 1)
            {
                KryptonPage kar = ((ButtonSpecAny)sender).Tag as KryptonPage;
                if (kar != null)
                {
                    TeighaBase basef = SelectDataGridView(kar);
                    if (basef != null)
                    {
                        basef.Invoker.Dispose();
                        if (basef.graphics != null)
                            basef.graphics.Dispose();
                        if (basef.helperDevice != null)
                            basef.helperDevice.Dispose();
                        if (basef.database != null)
                            basef.database.Dispose();
                        basef.Dispose();
                    }
                    kar.Dispose();
                }
            }
        }

        /// <summary>
        /// 查找BaseForms;
        /// </summary>
        /// <param name="Conl"></param>
        /// <returns></returns>
        public TeighaBase SelectDataGridView(Control Conl)
        {
            if (Conl == null)
                return null;
            foreach (Control item in Conl.Controls)
            {
                if (item is TeighaBase)
                {
                    return item as TeighaBase;
                }
                else
                    return SelectDataGridView(item);
            }
            return null;
        }


        #endregion

        #region 修改界面配色
        /// <summary>
        /// 修改配色
        /// </summary>
        public void bindblendent()
        {
            kryptonManager1.GlobalPaletteMode = (PaletteModeManager)System.Enum.Parse(typeof(PaletteModeManager), ConnectionStrings.GetAppConfig("Setinterface"), true);
            switch (kryptonManager1.GlobalPaletteMode)
            {
                case PaletteModeManager.ProfessionalSystem:
                    krypGroupblendent.SelectedIndex = 10;
                    break;
                case PaletteModeManager.ProfessionalOffice2003:
                    krypGroupblendent.SelectedIndex = 9;
                    break;
                case PaletteModeManager.Office2007Blue:
                    krypGroupblendent.SelectedIndex = 3;
                    break;
                case PaletteModeManager.Office2007Silver:
                    krypGroupblendent.SelectedIndex = 4;
                    break;
                case PaletteModeManager.Office2007Black:
                    krypGroupblendent.SelectedIndex = 5;
                    break;
                case PaletteModeManager.Office2010Blue:
                    krypGroupblendent.SelectedIndex = 0;
                    break;
                case PaletteModeManager.Office2010Silver:
                    krypGroupblendent.SelectedIndex = 1;
                    break;
                case PaletteModeManager.Office2010Black:
                    krypGroupblendent.SelectedIndex = 2;
                    break;
                case PaletteModeManager.SparkleBlue:
                    krypGroupblendent.SelectedIndex = 6;
                    break;
                case PaletteModeManager.SparkleOrange:
                    krypGroupblendent.SelectedIndex = 7;
                    break;
                case PaletteModeManager.SparklePurple:
                    krypGroupblendent.SelectedIndex = 8;
                    break;
                case PaletteModeManager.Custom:
                    krypGroupblendent.SelectedIndex = 11;
                    break;
                default:
                    break;
            }
            //UpdateCollapsedSizing();
            //skinEngine1.SkinFile = @"C:\Users\Administrator\Desktop\teigha_learning_project\Bin\Skins\Calmness.ssk";

        }

        private void krypGroupblendent_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (krypGroupblendent.SelectedIndex)
            {
                case 0:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.Office2010Blue;
                    break;
                case 1:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.Office2010Silver;
                    break;
                case 2:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.Office2010Black;
                    break;
                case 3:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.Office2007Blue;
                    break;
                case 4:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.Office2007Silver;
                    break;
                case 5:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.Office2007Black;
                    break;
                case 6:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.SparkleBlue;
                    break;
                case 7:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.SparkleOrange;
                    break;
                case 8:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.SparklePurple;
                    break;
                case 9:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.ProfessionalOffice2003;
                    break;
                case 10:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.ProfessionalSystem;
                    break;
                case 11:
                    kryptonManager1.GlobalPaletteMode = PaletteModeManager.Custom;
                    break;
                default:
                    break;
            }
            ConnectionStrings.modifyItem("Setinterface", kryptonManager1.GlobalPaletteMode.ToString());
            //UpdateCollapsedSizing();
        }

        #endregion

        #region 插入常见实体
        
        private void setStateGBnt(object obj)
        {
            if (CAD != null)
            {
                if (CAD.OperModel != Operations.None)
                {
                    KryptonRibbonGroupButton but = obj as KryptonRibbonGroupButton;
                    if (kryRibGButPen.Checked && kryRibGButPen!=but)
                        kryRibGButPen.Checked = false;
                    if (kryRibGButLine.Checked && kryRibGButLine != but)
                        kryRibGButLine.Checked = false;
                    if (kryRibGButPoliy.Checked && kryRibGButPoliy != but)
                        kryRibGButPoliy.Checked = false;
                    if (kryRibGButHu.Checked && kryRibGButHu != but)
                        kryRibGButHu.Checked = false;
                    if (kryRibGButArc.Checked && kryRibGButArc != but)
                        kryRibGButArc.Checked = false;
                    if (kryRibGButPoint.Checked && kryRibGButPoint != but)
                        kryRibGButPoint.Checked = false;
                }
                CAD.OperModel = Operations.None;
                CAD.basepanel.Cursor = Cursors.Default;
                CAD.DragSelected = false;

            }
        }
        
        private void kryRibGButPen_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButPen.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.DrawPebs(kryRibGButPen.Checked);
        }

        private void kryRibGButLine_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButLine.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(kryRibGButLine.Checked, EntityType.Line);
        }

        private void kryRibGButPoliy_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButPoliy.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(kryRibGButPoliy.Checked, EntityType.Mline);
        }

        private void kryRibGButHu_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButHu.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(kryRibGButHu.Checked, EntityType.Arc);
        }

        private void kryRibGButArc_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButArc.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(kryRibGButArc.Checked, EntityType.Circle);
        }

        private void kryRibButEllipse_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibButEllipse.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(kryRibButEllipse.Checked, EntityType.Ellipse);
        }

        private void kryRibGButPoint_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButPoint.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(kryRibGButPoint.Checked, EntityType.Point);
        }

        private void kryRibGButText_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButText.Checked)
                setStateGBnt(sender);
            //if (CAD != null)
            //    CAD.InsertLine(kryRibGButText.Checked, EntityType.te);
        }

        private void kryRibGButMtext_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryRibGButMtext.Checked)
                setStateGBnt(sender);
            //if (CAD != null)
            //    CAD.InsertLine(kryRibGButMtext.Checked, EntityType.Point);
        }

        /// <summary>
        /// 拖拽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void kryptonRibbonGroupButton4_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (kryptonRibbonDragBtn.Checked)
                setStateGBnt(sender);
            if (CAD != null)
                CAD.SetmouseTypeOk(kryptonRibbonDragBtn.Checked);
        }

        private void kryptonRibbonGroupButton6_Click(object sender, EventArgs e)
        {
            if (CAD != null)
                CAD.InsertDwfBy();
        }

        private void kryptonRibbonGroupButton5_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertImages();
        }

        private void kryptonRibbonGroupButton7_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.leader);
        }

        private void kryptonRibbonGroupButton8_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.LineDim);
        }
        private void kryptonDimAngleBtn_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.AngleLengthDim);
        }
        private void kryptonRibbonGroupButton13_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.ArcLenDim);
        }

        #region 角度值
        //倾斜
        private void KryptonContextMenuItem12_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.AnglerotaDim);
        }

        //直线
        private void KryptonContextMenuItem11_Click(object sender, EventArgs e)
        {
            if (CAD != null)
                CAD.InsertLine(true, EntityType.AngleLengthDim);
        }

        //圆弧
        private void KryptonContextMenuItem10_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.AngleArcDim);
        }
        #endregion

        private void kryptonRibbonGroupButton10_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.ArcDim);
        }

        private void kryptonRibbonGroupButton11_Click(object sender, EventArgs e)
        {
            setStateGBnt(sender);
            if (CAD != null)
                CAD.InsertLine(true, EntityType.Dimension);
        }

        private void kryptonRibbonGroupButton12_Click(object sender, EventArgs e)
        {
            if (CAD != null)
            {
                string StrText = KryptonInputBox.Show("请输入要添加的备注信息，无内容自动取消", "提示");
                if (!string.IsNullOrWhiteSpace(StrText))
                    CAD.AddEntity_Xdata(StrText);
            }
        }

        #endregion


        #region 面板移动
        private void OnUpDown(object sender, EventArgs e)
        {
            // Suspend layout changes until all splitter properties have been updated
            kryptonSplitContainer2.SuspendLayout();

            // Is the bottom right header group currently expanded?
            if (kryptonSplitContainer2.FixedPanel == FixedPanel.None)
            {
                // Make the bottom panel of the splitter fixed in size
                kryptonSplitContainer2.FixedPanel = FixedPanel.Panel2;
                kryptonSplitContainer2.IsSplitterFixed = true;

                // Remember the current height of the header group (to restore later)
                _heightUpDown = kryptonHeaderGroup3.Height;

                // Find the new height to use for the header group
                int newHeight = kryptonHeaderGroup3.PreferredSize.Height;

                // Make the header group fixed to the new height
                kryptonSplitContainer2.Panel2MinSize = newHeight;
                kryptonSplitContainer2.SplitterDistance = kryptonSplitContainer2.Height;
            }
            else
            {
                // Make the bottom panel not-fixed in size anymore
                kryptonSplitContainer2.FixedPanel = FixedPanel.None;
                kryptonSplitContainer2.IsSplitterFixed = false;

                // Put back the minimise size to the original
                kryptonSplitContainer2.Panel2MinSize = 100;

                // Calculate the correct splitter we want to put back
                kryptonSplitContainer2.SplitterDistance = kryptonSplitContainer2.Height - _heightUpDown - kryptonSplitContainer2.SplitterWidth;
            }

            kryptonSplitContainer2.ResumeLayout();
        }

        private void OnLeftRight(object sender, EventArgs e)
        {
            kryptonSplitContainer1.SuspendLayout();

            // Is the left header group currently expanded?
            if (kryptonSplitContainer1.FixedPanel == FixedPanel.None)
            {
                // Make the left panel of the splitter fixed in size
                kryptonSplitContainer1.FixedPanel = FixedPanel.Panel1;
                kryptonSplitContainer1.IsSplitterFixed = false;

                // Remember the current height of the header group
                _widthLeftRight0 = kryptonHeaderGroup1.Width;

                // We have not changed the orientation of the header yet, so the width of 
                // the splitter panel is going to be the height of the collapsed header group
                int newWidth = kryptonHeaderGroup1.PreferredSize.Height;

                // Make the header group fixed just as the new height
                kryptonSplitContainer1.Panel1MinSize = newWidth;
                kryptonSplitContainer1.SplitterDistance = newWidth;

                // Change header to be vertical and button to near edge
                kryptonHeaderGroup1.HeaderPositionPrimary = VisualOrientation.Right;
                kryptonHeaderGroup1.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Near;
            }
            else
            {
                // Make the bottom panel not-fixed in size anymore
                kryptonSplitContainer1.FixedPanel = FixedPanel.None;
                kryptonSplitContainer1.IsSplitterFixed = false;

                // Put back the minimise size to the original
                kryptonSplitContainer1.Panel1MinSize = 50;

                // Calculate the correct splitter we want to put back
                kryptonSplitContainer1.SplitterDistance = _widthLeftRight0;

                // Change header to be horizontal and button to far edge
                kryptonHeaderGroup1.HeaderPositionPrimary = VisualOrientation.Top;
                kryptonHeaderGroup1.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Far;
            }

            kryptonSplitContainer1.ResumeLayout();
        }

        private void GJInfo_OnLeftRight(object sender, EventArgs e)
        {
            InfoContainer.SuspendLayout();

            // Is the left header group currently expanded?
            if (InfoContainer.FixedPanel == FixedPanel.None)
            {
                // Make the left panel of the splitter fixed in size
                InfoContainer.FixedPanel = FixedPanel.Panel1;
                InfoContainer.IsSplitterFixed = false;

                // Remember the current height of the header group
                //_widthLeftRight = gjInfo.Width;
                _widthLeftRight = 265;
                // We have not changed the orientation of the header yet, so the width of 
                // the splitter panel is going to be the height of the collapsed header group
                int newWidth = gjInfo.PreferredSize.Height;

                // Make the header group fixed just as the new height
                InfoContainer.Panel1MinSize = newWidth;
                InfoContainer.SplitterDistance = newWidth;

                // Change header to be vertical and button to near edge
                gjInfo.HeaderPositionPrimary = VisualOrientation.Right;
                gjInfo.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Near;
            }
            else
            {
                // Make the bottom panel not-fixed in size anymore
                InfoContainer.FixedPanel = FixedPanel.None;
                InfoContainer.IsSplitterFixed = false;

                // Put back the minimise size to the original
                InfoContainer.Panel1MinSize = 50;

                // Calculate the correct splitter we want to put back
                InfoContainer.SplitterDistance = _widthLeftRight;
              
                // Change header to be horizontal and button to far edge
                gjInfo.HeaderPositionPrimary = VisualOrientation.Top;
                gjInfo.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Far;
                gjInfo.Panel.Refresh();
            }

            InfoContainer.ResumeLayout();
          
        }

        private void UpdateCollapsedSizing()
        {
            // Is the bottom right header group currently collapsed?
            if (kryptonSplitContainerVertical.FixedPanel == FixedPanel.Panel2)
            {
                // Suspend layout changes until all splitter properties have been updated
                kryptonSplitContainerHorizontal.SuspendLayout();

                // Get the new preferred height of the header group and apply it
                int newHeight = kryptonHeaderGroupRightBottom.PreferredSize.Height;
                kryptonSplitContainerVertical.Panel2MinSize = newHeight;
                kryptonSplitContainerVertical.SplitterDistance = kryptonSplitContainerVertical.Height;

                kryptonSplitContainerHorizontal.ResumeLayout();
            }

            // Is the left header group currently collapsed?
            if (kryptonSplitContainerHorizontal.FixedPanel == FixedPanel.Panel1)
            {
                // Suspend layout changes until all splitter properties have been updated
                kryptonSplitContainerVertical.SuspendLayout();

                // Get the new preferred width of the header group and apply it
                int newWidth = kryptonHeaderGroupLeft.PreferredSize.Width;
                kryptonSplitContainerHorizontal.Panel1MinSize = newWidth;
                kryptonSplitContainerHorizontal.SplitterDistance = newWidth;

                kryptonSplitContainerVertical.ResumeLayout();
            }
        }

        #endregion

        public void CheckIsExistTgBase()
        {
            //KryptonPageCollection krylist = kryNavigators.Pages;
            //if(krylist==null|| krylist.Count==0)
            //{
            //    string tempFile = System.IO.Path.GetTempFileName();
            //    //string tempFile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Temp\\" + "Drawing1.dwg";
            //    string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Template\\dwgModel.dwg";
            //    FileInfo info = new FileInfo(path);
            //    info.CopyTo(tempFile, true);
            //    GlobleFunc.tempDwgPath = tempFile;
            //    Load_the_dwgordxf(tempFile, false);
            //}
            //else
            //{
            //    kryNavigators.Pages.Clear();
            //    //TeighaBase.getInstance().database.Redo();
            //    string dic = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Temp\\";
            //    int num = Directory.GetFiles(dic).Length > 0 ? Directory.GetFiles(dic).Length + 1 : 1;
            //    string tempFile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Temp\\" + "Drawing" + num + ".dwg";
            //    //string tempFile = System.IO.Path.GetTempFileName();
            //    string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Template\\dwgModel.dwg";
            //    FileInfo info = new FileInfo(path);
            //    info.CopyTo(tempFile, true);
            //    GlobleFunc.tempDwgPath = tempFile;
            //    Load_the_dwgordxf(tempFile, false);
            //}
            KryptonPageCollection krylist = kryNavigators.Pages;
            if (krylist == null || krylist.Count == 0)
            {
            }
            else
            {
                kryNavigators.Pages.Clear();
            }
            string tempFile = System.IO.Path.GetTempFileName();
            //string tempFile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Temp\\" + "Drawing1.dwg";
            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Template\\dwgModel.dwg";
            FileInfo info = new FileInfo(path);
            info.CopyTo(tempFile, true);
            GlobleFunc.tempDwgPath = tempFile;
            Load_the_dwgordxf(tempFile, false);
            kryNavigators.Refresh();

        }


        private void kryptonSplitContainer2_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        //DataRow row = null;
        //double selectScale = 1;
        private void pileCapBtn_Click(object sender, EventArgs e)
        {
            bool isDrawing = false;
            InitPileCapTree();

            //bool isDrawing = false;
            //CAD.SelectDrawingSubstructure(SubstructureType.PileCap, ref row, ref selectScale,ref isDrawing);
            //if (isDrawing)
            //{
            //    CheckIsExistTgBase();
            //    SingleCAD.getInstance(this).SetPageModel();
            //    Tools.ClearDatabase();
            //    InitGJTree(SubstructureType.PileCap);
            //    InitGJInfo(SubstructureType.PileCap, row, selectScale);
            //    CAD.DrawingSubstructure(SubstructureType.PileCap, row, selectScale);
            //}

        }

        private void pileBtn_Click(object sender, EventArgs e)
        {                
            bool isDrawing = false;
            InitPileTree();

            //CAD.SelectDrawingSubstructure(SubstructureType.Pile, ref row, ref selectScale, ref isDrawing);
            //if (isDrawing)
            //{
          

   
            //}
        }
        public void InitPileCapTree()
        {
            gjTree.Nodes.Clear();
            TreeNode gen1 = new TreeNode("承台");
            TreeNode sg1 = new TreeNode("承台");
            string sql = "select  * from t_pile_cap_reinforcement where  status=0  order by create_time desc";
            System.Data.DataTable dt = MySqlHelper.ExecuteDataTable(sql, CommandType.Text);
            if (dt.Rows.Count > 0)
            {
                gjTree.Nodes.Add(gen1);
                foreach (DataRow row in dt.Rows)
                {
                    sg1 = new TreeNode();
                    //给根节点赋值
                    sg1.Tag = row;
                    sg1.Text = row["configure_name"].ToString();
                    gen1.Nodes.Add(sg1);

                }
                InitGJInfo(SubstructureType.PileCap, dt.Rows[0], 5);
            }
            else
            {
                InitGJInfo(SubstructureType.PileCap);
            }


            //把节点添加进TreeView控件中

            gjTree.ExpandAll();
        }
        public void InitPileTree()
        {
            gjTree.Nodes.Clear();
            TreeNode gen1 = new TreeNode("桩基");
            TreeNode sg1 = new TreeNode("桩基");
            string sql = "select  * from t_pile_info_reinforcement where  status=0  order by create_time desc";
            System.Data.DataTable dt = MySqlHelper.ExecuteDataTable(sql, CommandType.Text);
            if (dt.Rows.Count > 0)
            {
                gjTree.Nodes.Add(gen1);
                foreach (DataRow row in dt.Rows)
                {
                    sg1 = new TreeNode();
                    //给根节点赋值
                    sg1.Tag = row;
                    sg1.Text = row["configure_name"].ToString();
                    gen1.Nodes.Add(sg1);
                  
                }
                InitGJInfo(SubstructureType.Pile, dt.Rows[0], 5);
            }
            else
            {
                InitGJInfo(SubstructureType.Pile);
            }
           

            //把节点添加进TreeView控件中
          
            gjTree.ExpandAll();
        }
        
        private void kryptonRibbonPlinthBtn_Click(object sender, EventArgs e)
        {
           
            //bool isDrawing = false;
            //CAD.SelectDrawingSubstructure(SubstructureType.Plinth, ref row, ref selectScale, ref isDrawing);
            //if (isDrawing)
            //{
            //    CheckIsExistTgBase();
            //    SingleCAD.getInstance(this).SetPageModel();

            //    Tools.ClearDatabase();
            //    InitGJTree(SubstructureType.Plinth);
            //    InitGJInfo(SubstructureType.Plinth, row, selectScale);
            //    CAD.DrawingSubstructure(SubstructureType.Plinth, row, selectScale);
            //}
        }

        SubstructureType _type = SubstructureType.Pile;
        public void InitGJTree(SubstructureType type)
        {
            gjTree.Nodes.Clear();
            TreeNode gen1 = new TreeNode("单独构件");
            TreeNode sg1 = new TreeNode("桩基");
            switch (type)
            {
                case SubstructureType.PileCap:
                    sg1 = new TreeNode("承台");
                    break;
                case SubstructureType.Pile:
                    sg1 = new TreeNode("桩基");
                    break;
                case SubstructureType.Plinth:
                    sg1 = new TreeNode("垫石");
                    break;
            }
            //把节点添加进TreeView控件中
            gen1.Nodes.Add(sg1);
            gjTree.Nodes.Add(gen1);          
            gjTree.ExpandAll();
            _type = type;
        }
        private void InitGJInfo(SubstructureType type, DataRow row,double scale)
        {
            gjInfo.Panel.Controls.Clear();
            GJInfoForm EditEnt = new GJInfoForm(this, type, row, scale);
            EditEnt.Send_GJConfirmBefore += EditEnt_Send_GJConfirmBefore;
            EditEnt.Send_GJConfirm += EditEnt_Send_GJConfirm;
            EditEnt.TopLevel = false;
            EditEnt.Dock = DockStyle.Fill;
            EditEnt.Activate();
            //DBForm.ContextMenuStrip = contextMenu;
            EditEnt.FormBorderStyle = FormBorderStyle.None;
            InfoContainer.Panel1Collapsed = false;
            gjInfo.Panel.Controls.Add(EditEnt);
            gjInfo.AutoSize = true;
            InfoContainer.SplitterDistance = 265;
            EditEnt.Show();
            gjInfo.Refresh();
            _type = type;
            InfoContainer.Refresh();
        }
        private void InitGJInfo(SubstructureType type)
        {
            gjInfo.Panel.Controls.Clear();
            GJInfoForm EditEnt = new GJInfoForm(this, type);   
            EditEnt.Send_GJConfirmBefore += EditEnt_Send_GJConfirmBefore;
            EditEnt.Send_GJConfirm += EditEnt_Send_GJConfirm; 
            EditEnt.TopLevel = false;
            EditEnt.Dock = DockStyle.Fill;
            EditEnt.Activate();
            //DBForm.ContextMenuStrip = contextMenu;
            EditEnt.FormBorderStyle = FormBorderStyle.None;
            InfoContainer.Panel1Collapsed = false;
            gjInfo.Panel.Controls.Add(EditEnt);
            gjInfo.AutoSize = true;
            InfoContainer.SplitterDistance = 265;
            EditEnt.Show();
            gjInfo.Refresh();
            InfoContainer.Refresh();
        }


        private void InitSubstructureInfo()
        {
            gjInfo.Panel.Controls.Clear();
            SubstructureForm EditEnt = new SubstructureForm(this);
            EditEnt.Send_ConfirmBefore += EditEnt_Send_ConfirmBefore;
            EditEnt.Send_Confirm += EditEnt_Send_Confirm; ;
            EditEnt.TopLevel = false;
            EditEnt.Dock = DockStyle.Fill;
            EditEnt.Activate();
            //DBForm.ContextMenuStrip = contextMenu;
            EditEnt.FormBorderStyle = FormBorderStyle.None;
            InfoContainer.Panel1Collapsed = false;
            gjInfo.Panel.Controls.Add(EditEnt);
            gjInfo.AutoSize = true;
            InfoContainer.SplitterDistance = 265;
            EditEnt.Show();
            gjInfo.Refresh();
            InfoContainer.Refresh();
        }

        private void EditEnt_Send_Confirm(string paraFile, string saveFolder, PierSubstructureType type)
        {
            CAD.DrawingPierSubstructure(paraFile, saveFolder, type);
        }

        private void EditEnt_Send_ConfirmBefore()
        {
            CheckIsExistTgBase();
            SingleCAD.getInstance(this).SetPageModel();
            Tools.ClearDatabase();
            gjInfo.Refresh();
            InfoContainer.Refresh();
        }

        private void EditEnt_Send_GJConfirm(DataRow mySelectRow, double selectScale)
        {
            //InitPileTree();

            switch (_type)
            {
                case SubstructureType.PileCap:
                    CAD.DrawingSubstructureNew(SubstructureType.PileCap, mySelectRow, selectScale);
                    break;
                case SubstructureType.Pile:
                    CAD.DrawingSubstructureNew(SubstructureType.Pile, mySelectRow, selectScale);
                    break;
                case SubstructureType.Plinth:

                    break;

            }

        }

        private void EditEnt_Send_GJConfirmBefore()
        {
            CheckIsExistTgBase();
            //CheckIsExistTgBase();
            SingleCAD.getInstance(this).SetPageModel();
            Tools.ClearDatabase();
        }
      

        private void configBtn_Click(object sender, EventArgs e)
        {
            SystemConfigForm frm = new SystemConfigForm();
            frm.ShowDialog();
            if(frm.DialogResult==DialogResult.OK)
            {
                MessageBox.Show("设置成功！", "提示");
            }
            else
            {

            }
        }

        private void gjTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = e.Node;
            if (node.Tag != null)
            {
                switch (_type)
                {
                    case SubstructureType.PileCap:
                        string sqlPileCap = "select  * from t_pile_cap_reinforcement where  status=0 and id=" + ((DataRow)node.Tag)["id"] + " order by create_time desc";
                        System.Data.DataTable dtPileCap = MySqlHelper.ExecuteDataTable(sqlPileCap, CommandType.Text);

                        if (dtPileCap.Rows.Count > 0)
                        {
                            node.Tag = dtPileCap.Rows[0];
                        }
                        InitGJInfo(SubstructureType.PileCap, (DataRow)node.Tag, 5);
                        break;
                    case SubstructureType.Pile:
                        string sql = "select  * from t_pile_info_reinforcement where  status=0 and id="+ ((DataRow)node.Tag)["id"]+ " order by create_time desc";
                        System.Data.DataTable dt = MySqlHelper.ExecuteDataTable(sql, CommandType.Text);
                        
                        if (dt.Rows.Count > 0)
                        {
                            node.Tag = dt.Rows[0];
                        }
                        InitGJInfo(SubstructureType.Pile, (DataRow)node.Tag, 5);
                        break;
                    case SubstructureType.Plinth:

                        break;
                }
            }
        }


        private void gjTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 显示右键菜单
                contextGJTreeMenu.Show(gjTree, e.Location);
            }
        }

        private void add_Click(object sender, EventArgs e)
        {
            switch (_type)
            {
                case SubstructureType.PileCap:
                    InitGJInfo(SubstructureType.PileCap);
                    break;
                case SubstructureType.Pile:
                    InitGJInfo(SubstructureType.Pile);
                    break;
                case SubstructureType.Plinth:
                   
                    break;
            }
        }

        private void modify_Click(object sender, EventArgs e)
        {
            TreeNode node = gjTree.SelectedNode;
            if (node.Tag != null)
            {
                switch (_type)
                {
                    case SubstructureType.PileCap:
                        InitGJInfo(SubstructureType.PileCap, (DataRow)node.Tag, 5);
                        break;
                    case SubstructureType.Pile:
                        InitGJInfo(SubstructureType.Pile, (DataRow)node.Tag, 5);
                        break;
                    case SubstructureType.Plinth:

                        break;
                }
            }
        }

        private void delete_Click(object sender, EventArgs e)
        {
            TreeNode node = gjTree.SelectedNode;
            if (node.Tag != null)
            {
                switch (_type)
                {
                    case SubstructureType.PileCap:
                        string delPileCap = "update t_pile_cap_reinforcement set status=1 where id='" + ((DataRow)node.Tag)["id"] + "'";
                        MySqlHelper.ExecuteNonQuery(delPileCap, CommandType.Text);
                        InitPileCapTree();
                        break;
                    case SubstructureType.Pile:
                        string delP = "update t_pile_info_reinforcement set status=1 where id='"+ ((DataRow)node.Tag)["id"]+ "'";
                        MySqlHelper.ExecuteNonQuery(delP, CommandType.Text);
                        InitPileTree();
                        break;
                    case SubstructureType.Plinth:

                        break;
                }
                MessageBox.Show("删除成功！", "提示");
            }
        }
    }
}
